<template>
  <view v-if="visible" :class="['error-message', typeClass]" @click="close" role="alert">
    {{ message }}
  </view>
</template>

<script>
export default {
  name: 'ErrorMessage',
  props: {
    message: {
      type: String,
      required: true,
    },
    visible: {
      type: Boolean,
      required: true,
    },
    type: {
      type: String,
      default: 'error', // 默认类型为 error
    },
  },
  data() {
    return {
      closeTimeout: null, // 定义一个用于存储定时器ID的变量
    };
  },
  computed: {
    typeClass() {
      return `error-message--${this.type}`; // 根据类型动态改变样式
    },
  },
  watch: {
    visible(newValue) {
      if (newValue) {
        this.autoClose(); // 在可见时启动自动关闭
      } else {
        this.clearCloseTimeout(); // 隐藏时清除定时器
      }
    },
  },
  mounted() {
    if (this.visible) {
      this.autoClose();
    }
  },
  beforeDestroy() {
    this.clearCloseTimeout(); // 清理定时器以防内存泄漏
  },
  methods: {
    autoClose() {
      this.clearCloseTimeout(); // 清除旧的定时器
      this.closeTimeout = setTimeout(() => {
        this.close();
      }, 2000);
    },
    clearCloseTimeout() {
      if (this.closeTimeout) {
        clearTimeout(this.closeTimeout); // 清除定时器
        this.closeTimeout = null; // 重置定时器ID
      }
    },
    close() {
      this.$emit('update:visible', false);
    },
  },
};
</script>

<style scoped>
.error-message {
  background-color: #f44336;
  color: white;
  padding: 20rpx;
  border-radius: 10rpx;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.error-message--success {
  background-color: #d4edda;
  color: #155724;
}

.error-message--warning {
  background-color: #fff3cd;
  color: #856404;
}

.error-message--info {
  background-color: #cce5ff;
  color: #004085;
}
</style>